Skip to main content

UiButton

A clickable UI element that displays either text or a sprite, supporting automatic resizing, hover effects, and flexible alignment.


Constructor

new UiButton(textOrImage, style = {}, props = {})

Parameters

NameTypeDescription
textOrImagestringsprite
stylestructFlexPanel layout style (width, height, margins, etc.).
propsstructAdditional configuration such as outline, autoResize, and halign.

Properties

PropertyTypeDescription
textstringundefined
spritespriteundefined
autoResizebooleanAutomatically adjusts size to fit content. Defaults to true.
outlinebooleanDraws an outline instead of a filled background.
halignconstantHorizontal alignment (fa_left, fa_center, fa_right). Default center.
handpointbooleanShows a hand cursor when hovering (UI convenience flag).
pointerEventsbooleanEnables pointer interaction (always true for buttons).
hoveredbooleanTrue when the mouse is over the button.

Methods

MethodReturnsDescription
resize()voidUpdates width and height to fit text or sprite content.
setText(text)voidSets the button text and resizes it automatically.
setSprite(sprite)voidSets the button sprite and resizes it automatically.

Drawing Behavior

The button automatically redraws when hovered or when its state changes. It uses the global UI color palette:

ConstantDescription
global.UI_COL_BTN_HOVERBackground color when hovered.
global.UI_COL_BOXNormal background or outline color.

If text is defined, the button draws centered text using fText. If sprite is defined instead, it draws the sprite centered on the button, switching to subimage 1 when hovered.

Example

var btn = new UiButton("Click me", { left: 10, top: 10 });
btn.onClick(function() {
show_debug_message("Button clicked!");
});
global.UI.add(btn);

Or with a sprite-based button:

var btn = new UiButton(spr_button);
btn.onClick(function() {
show_debug_message("Sprite button pressed!");
});

Notes

  • Automatically resizes based on its content, avoiding manual layout updates.